package com.webserver1.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method,uir,protocol,requestURI,questString;

    private Map<String,String> headers = new HashMap<>();

    private Map<String,String> parameters = new HashMap<>();

    public HttpServletRequest(Socket socket) throws EmptyRequestException, IOException {
        this.socket = socket;
        parseRequestLine();//解析请求行
        parseHeaders();//解析请求头
        parseContent();//解析消息正文
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {//解析请求行
        String line = readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();//抛出空请求异常
        }
        String[] data = line.split("\\s");
        method = data[0];
        uir = data[1];
        parseURI();//进一步解析uir
        protocol = data[2];
    }

    private void parseURI(){//进一步解析uir
        if (uir.indexOf("?") == -1){
            requestURI = uir;
        }else {
            String[] data = uir.split("\\?");
            requestURI = data[0];
            questString = data[1];
            try {
                questString = URLDecoder.decode(questString,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String[] f = questString.split("&");
            for (int i = 0;i<f.length;i++){
                String[] query = f[i].split("=",2);
                parameters.put(query[0],query[1]);
            }
        }
    }
    private void parseHeaders() throws IOException {//解析请求头
        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            String[] data = line.split("\\s");
            headers.put(data[0],data[1] );
        }
    }
    private void parseContent(){}//解析消息正文。
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char pre = 'a',cur = 'a';
        int d ;
        while ((d = in.read()) !=-1){
            cur = (char) d;
            if (pre==13 && cur==10){
                break;
            }
            builder.append(d);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUir() {
        return uir;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQuestString() {
        return questString;
    }

    public String getHeaders(String name) {
        return headers.get(name);
    }
}
